﻿namespace VividKit.ServiceModel
{
	using System;
	using System.Diagnostics;
	using System.Threading.Tasks;

	public class TraceQueryDispatcher : IQueryDispatcher
	{
		private readonly IQueryDispatcher queryDispatcher;

		public TraceQueryDispatcher(IQueryDispatcher queryDispatcher)
		{
			this.queryDispatcher = queryDispatcher;
		}

		public TResult Run<TResult>(IQuery<TResult> query)
		{
			var stopwatch = new Stopwatch();
			try
			{
				Debug.WriteLine("Running {0}", query.GetType().Name);

				stopwatch.Start();
				return this.queryDispatcher.Run(query);
			}
			catch (Exception x)
			{
				Debug.WriteLine(x.ToString());
				throw;
			}
			finally
			{
				stopwatch.Stop();
				Debug.WriteLine("Ran {0} ({1} ms)",
					query.GetType().Name, stopwatch.ElapsedMilliseconds);
			}
		}

		public async Task<TResult> RunAsync<TResult>(IQuery<TResult> query)
		{
			var stopwatch = new Stopwatch();
			try
			{
				Debug.WriteLine("Running {0}", query.GetType().Name);

				stopwatch.Start();
				return await this.queryDispatcher.RunAsync(query);
			}
			catch (Exception x)
			{
				Debug.WriteLine(x.ToString());
				throw;
			}
			finally
			{
				stopwatch.Stop();
				Debug.WriteLine("Ran {0} ({1} ms)",
					query.GetType().Name, stopwatch.ElapsedMilliseconds);
			}
		}
	}
}